package com.xianggg.xservers.weixin;

import com.xianggg.xservers.weixin.sdk.WeChatAPI;
import com.xianggg.xservers.weixin.sdk.type.EventType;
import com.xianggg.xservers.weixin.sdk.type.MsgType;
import com.xianggg.xservers.weixin.sdk.vo.InputMsg;
import com.xianggg.xservers.weixin.sdk.vo.OutputTextMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("msg")
public class WxMsgController {
    private final static Logger logger = LoggerFactory.getLogger(WxMsgController.class);

    /**
     * 微信端get认证 回复
     */
    @RequestMapping(value = "reply", method = RequestMethod.GET)
    public String reply(HttpServletRequest request) {
        //get方法为微信验证接口
        //微信加密签名，signature结合了开发者填写的token参数
        // 和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        return request.getParameter("echostr");
    }

    /**
     * 微信回复post消息
     */
    @RequestMapping(value = "reply", method = RequestMethod.POST)
    public String replyPostMsg(HttpServletRequest request, HttpServletResponse response) {
        String replyXml = "success";
        try {
            InputMsg inputMsg = WeChatAPI.msgParse(request, response);
            MsgType inputMsgType = MsgType.valueOf(inputMsg.getMsgType());
            OutputTextMsg outputTextMsg;
            switch (inputMsgType){
                case text:
                    outputTextMsg = WeChatAPI.replyMsg(inputMsg, "点击【查看报告】可查看学生做题情况");
                    replyXml = WeChatAPI.replyXml(outputTextMsg, OutputTextMsg.class);
                    break;
                case event:
                    if(EventType.subscribe.name().equals(inputMsg.getEvent())) {
                        outputTextMsg = WeChatAPI.replyMsg(inputMsg, "您好！欢迎关注创数学习通！");
                        replyXml = WeChatAPI.replyXml(outputTextMsg, OutputTextMsg.class);
                    }
                    break;
            }
        } catch (IOException e) {
            logger.error("回复消息失败,传入消息格式有误", e);
        }
        return replyXml;
    }
}
